import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';
import 'package:photo_frame/base/AbsLifecycleState.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/pages/me/widget/me_avatar_cell.dart';
import 'package:photo_frame/pages/me/widget/me_item_cell.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/global_shared_preferences.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:photo_frame/widgets/app_bar_widget.dart';
import 'package:photo_frame/widgets/app_dialog.dart';
import 'package:photo_frame/widgets/custom_cupertino_alert_dialog.dart';
import 'package:provider/provider.dart';

import '../../utils/a_logger.dart';

class MePage extends StatefulWidget {
  @override
  State<MePage> createState() => _MePageState();
}

class _MePageState extends AbsLifecycleState<MePage>
    with AutomaticKeepAliveClientMixin {
  _MeProvider _meProvider = _MeProvider();

  GlobalKey<RefreshIndicatorState> refreshIndicatorStateKey = GlobalKey();

  @override
  void onResume() {
    super.onResume();
    if (_meProvider._pick) {
      return;
    }
    refreshIndicatorStateKey.currentState?.show();
  }

  @override
  void dispose() {
    // _meProvider.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: commonAppBar(appLocalForContext(context).me, hideBack: true),
      body: SafeArea(
          child: ChangeNotifierProvider(
              create: (context) => _meProvider,
              child: Container(
                color: Color(0xffF2F2F2),
                width: double.infinity,
                height: double.infinity,
                child: Padding(
                  padding: const EdgeInsets.only(left: 16.0, right: 16),
                  child: RefreshIndicator(
                    key: refreshIndicatorStateKey,
                    color: Color(0xff3F74EF),
                    onRefresh: () async {
                      return await _meProvider.syncUserInfo();
                    },
                    child: SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Consumer<_MeProvider>(
                              builder: (context, meProvider, child) {
                            return MeAvatarCell(
                              avatar: meProvider.getAvatar(),
                              avatarColor: meProvider.getAvatarColor(),
                              name: meProvider.getName(),
                              email: meProvider.getEmail(),
                              pickAvatar: () {
                                meProvider.showActionSheet(context);
                              },
                              editNickname: () {
                                meProvider.showEditNicknameDialog(context);
                              },
                            );
                          }),
                          SizedBox(height: 20),
                          Text(appLocalForContext(context).userInfoTitle),
                          Consumer<_MeProvider>(
                              builder: (context, meProvider, child) {
                            return MeItemCell(
                              leading: MeItemIcon("images/icon_mail.png"),
                              middle: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                      appLocalForContext(context)
                                          .uesrInfoEmailTitle,
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xff555555))),
                                  Text(meProvider.getEmail() ?? "",
                                      style: TextStyle(
                                          fontSize: 14,
                                          color: Color(0xff555555)))
                                ],
                              ),
                            );
                          }),
                          MeItemCell(
                            leading: MeItemIcon("images/icon_lock.png"),
                            title:
                                appLocalForContext(context).changePasswordTitle,
                            tailing: MeItemArrow(),
                            routerPath: "/forgetPassword",
                          ),
                          SizedBox(height: 20),
                          Text(appLocalForContext(context).settingAndHelpTitle),
                          MeItemCell(
                            leading: MeItemIcon("images/icon_history.png"),
                            title: appLocalForContext(context).sendRecord,
                            tailing: MeItemArrow(),
                            routerPath: "/sendAssetRecord",
                          ),
                          Consumer<_MeProvider>(
                              builder: (context, meProvider, child) {
                            return MeItemCell(
                                leading: MeItemIcon("images/icon_alarm.png"),
                                title: appLocalForContext(context)
                                    .notificationTitle,
                                tailing: CupertinoSwitch(
                                  activeColor: Color(0xff3F74EF),
                                  value: _meProvider.notificationSwitch,
                                  onChanged:
                                      _meProvider.changeNotificationSwitch,
                                ));
                          }),
                          MeItemCell(
                            leading: MeItemIcon("images/icon_question.png"),
                            title: appLocalForContext(context).helpTitle,
                            tailing: MeItemArrow(),
                            routerPath: "/help",
                          ),
                          MeItemCell(
                            leading: MeItemIcon("images/icon_info.png"),
                            title: appLocalForContext(context).aboutTitle,
                            tailing: MeItemArrow(),
                            routerPath: "/about",
                          ),
                          SizedBox(
                            height: 12,
                          )
                        ],
                      ),
                    ),
                  ),
                ),
              ))),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _MeProvider extends ChangeNotifier {
  String? _nickname;
  bool notificationSwitch =
      (GlobalSharedPreferences.instance.sp.getBool("notificationSwitch")) ==
          true;
  late final ImagePicker _picker = ImagePicker();
  bool _pick = false;

  String? getAvatar() {
    return UserManager.instance.getAvatar();
  }

  String? getEmail() {
    return UserManager.instance.getEmail();
  }

  int? getAvatarColor() {
    return UserManager.instance.getAvatarColor();
  }

  String? getName() {
    return UserManager.instance.getName();
  }

  pickImageFromGallery() async {
    try {
      _pick = true;
      XFile? imageXFile = await _picker.pickImage(
          source: ImageSource.gallery,
          imageQuality: 50,
          requestFullMetadata: false);
      await uploadAvatar(imageXFile);
    } catch (e) {
      print(e);
    } finally {
      _pick = false;
    }
  }

  pickImageFromCamera() async {
    try {
      _pick = true;
      XFile? imageXFile = await _picker.pickImage(
          source: ImageSource.camera,
          imageQuality: 50,
          requestFullMetadata: false);
      await uploadAvatar(imageXFile);
    } catch (e) {
      print(e);
    } finally {
      _pick = false;
    }
  }

  uploadAvatar(XFile? file) async {
    if (file == null) {
      Fluttertoast.showToast(msg: appLocal().takeAvatarFail);
      return;
    }
    EasyLoading.show(
      maskType: EasyLoadingMaskType.black,
    );
    var suffix = file.path.substring(file.path.lastIndexOf(".") + 1);
    if (suffix.isNotEmpty != true) {
      suffix = "jpg";
    }
    var response = await HttpManager.instance
        .doRequest("/info/avatar", parameters: {"ext": "$suffix"});
    if (!response.isSuccess) {
      EasyLoading.dismiss();
      Fluttertoast.showToast(msg: response.msg ?? "");
      return;
    }

    var uploadUrl = response.data?["uploadurl"];
    if (uploadUrl == null || uploadUrl.isEmpty) {
      EasyLoading.dismiss();
      Fluttertoast.showToast(msg: appLocal().getUploadUrlFail);
      return;
    }
    print(uploadUrl);
    HttpManager.instance.dio
        .request(uploadUrl,
            options: Options(method: "PUT", headers: {
              'Content-Type': 'image/jpeg', // or the appropriate content type
            }),
            data: await file.readAsBytes())
        .then((value) {
      EasyLoading.dismiss();
      print(value);
      syncUserInfo();
      //上报
      HttpManager.instance.doRequest("/info/avatarfinish");
    }).catchError((e) {
      print(e);
      EasyLoading.dismiss();
      Fluttertoast.showToast(msg: appLocal().uploadAvatarFail);
    });
  }

  void showActionSheet(BuildContext context) {
    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) => CupertinoActionSheet(
        actions: <CupertinoActionSheetAction>[
          CupertinoActionSheetAction(
            child: Text(appLocalForContext(context).takePhoto,
                style: TextStyle(color: Color(0xff3f74ef), fontSize: 16)),
            onPressed: () {
              Navigator.pop(context);
              pickImageFromCamera();
            },
          ),
          CupertinoActionSheetAction(
            child: Text(appLocalForContext(context).takePhotoFromLocal,
                style: TextStyle(color: Color(0xff3f74ef), fontSize: 16)),
            onPressed: () {
              Navigator.pop(context);
              pickImageFromGallery();
            },
          ),
        ],
      ),
    );
  }

  showEditNicknameDialog(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: true,
        builder: (BuildContext context) {
          return CustomCupertinoAlertDialog(
            title: Text(
              appLocalForContext(context).renameNicknameTitle,
              style: TextStyle(
                  fontSize: 16,
                  color: Color(0xff333333),
                  fontWeight: FontWeight.bold),
            ),
            content: Column(
              children: [
                Container(
                  margin: EdgeInsets.only(top: 8.5),
                  height: 44,
                  padding: EdgeInsets.symmetric(horizontal: 14),
                  decoration: BoxDecoration(
                      color: Color(0xffEAECEE),
                      borderRadius: BorderRadius.circular(10.0)),
                  child: TextField(
                    maxLines: 1,
                    minLines: 1,
                    cursorColor: Color(0xff3F74EF),
                    // 设置光标颜色
                    style:
                        TextStyle(fontWeight: FontWeight.normal, fontSize: 14),
                    decoration: InputDecoration(
                      hintMaxLines: 1,
                      border: InputBorder.none,
                      hintText: appLocalForContext(context).enterNewNickname,
                      hintStyle: TextStyle(
                        color: Colors.grey,
                        fontSize: 14,
                      ),
                    ),
                    onChanged: (value) {
                      _nickname = value;
                    },
                  ),
                ),
                SizedBox(height: 10),
              ],
            ),
            actions: [
              CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text(
                  appLocalForContext(context).cancel,
                  style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff333333),
                      fontWeight: FontWeight.bold),
                ),
              ),
              CupertinoButton(
                padding: EdgeInsets.zero,
                onPressed: () async {
                  if (_nickname == null || _nickname!.isEmpty) {
                    EasyLoading.showToast(
                        appLocalForContext(context).enterVaildNickname);
                    return;
                  }
                  EasyLoading.show(
                    maskType: EasyLoadingMaskType.black,
                  );
                  var response = await HttpManager.instance
                      .doRequest("/info/edit", parameters: {"name": _nickname});
                  if (!response.isSuccess) {
                    EasyLoading.dismiss();
                    EasyLoading.showToast(response.msg ?? "");
                  }
                  await UserManager.instance.syncUserInfo();
                  Navigator.pop(context);
                  EasyLoading.dismiss();
                  notifyListeners();
                },
                child: Text(
                  appLocalForContext(context).confirm,
                  style: TextStyle(
                      fontSize: 16,
                      color: Color(0xff3F74EF),
                      fontWeight: FontWeight.bold),
                ),
              ),
            ],
          );
        });
  }

  syncUserInfo() async {
    await UserManager.instance.syncUserInfo();

    notifyListeners();
  }

  changeNotificationSwitch(bool notificationSwitch) {
    ALogger.e("asdasdas ${notificationSwitch}");
    this.notificationSwitch = notificationSwitch;
    notifyListeners();
    GlobalSharedPreferences.instance.sp
        .setBool("notificationSwitch", notificationSwitch);
  }
}
